package com.sctvcloud.dongqu.ui.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.TitlePagerChangeListener;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.beans.CaliItem;
import com.sctvcloud.dongqu.beans.FocusColumn;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.CaligrapherPagerAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.BannerHolder;
import com.sctvcloud.dongqu.ui.utils.GlideUtil;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 首页频道页
 */
public class HuachengFragment extends ColumnBaseFragment implements OnTabSelectListener {
    public static final int VIEWTYPE_BANNER = 1;//轮播图
    public static final int VIEWTYPE_NEWS = 6;//文旅新闻item

    @BindView(R.id.view_pager)
    protected ViewPager viewPager;
    @BindView(R.id.tab_layout)
    protected SlidingTabLayout tabLayout;
    @BindView(R.id.news_convenientBanner)
    protected ConvenientBanner banner;
    @BindView(R.id.iv_banner)
    protected CustomEXImageView ivPic;
    @BindView(R.id.title_bg)
    protected ImageView titleBg;
    @BindView(R.id.left_title)
    protected TextView leftTitle;
    @BindView(R.id.tv_banner_title)
    protected CustomFontTextView tvTitle;
    @BindView(R.id.banner_layout)
    protected RelativeLayout bannerlayout;

    private List<NewsItem> channelBeanList;

    private String  bannerUrlTemp;

    List<FocusColumn> subList= new ArrayList<>();

    private CaligrapherPagerAdapter adapter;

    private List<CaliItem> dataList = new ArrayList<>();

    private String channelId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_huacheng, container, false);
        ButterKnife.bind(this, view);
        JLog.e("Cali页onCreateView!");
        return view;
    }

    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            channelId = arguments.getString("channelId", "");
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//        fragmentManager = getChildFragmentManager();
        super.onViewCreated(view, savedInstanceState);
        JLog.e("Cali页onViewCreated!");
        getCaliData();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        isCoverStatusColor = true;
        if (!hidden) {
            getCaliData();
        }
    }


    private boolean isRequesting = false;

    int aaa = 0;

    /**
     * 获取频道相关数据
     */
    private void getCaliData() {


        if (isRequesting) {
            return;
        }
        JLog.e("getCalliData=" + channelUrl);
        if (TextUtils.isEmpty(channelUrl)) {
            toast(R.string.data_wrong);
            return;
        }
        aaa++;
        JLog.e("getCalliData count=" + aaa);
        isRequesting = true;
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
/*                JLog.e("getTvData=onSuconSuconSuc");
                if (tv != null) {
                    caligrapherDataList = tv;
                    initCaliData(tv);
                }
*/

                if (ListUtils.isListValued(focusColumns)) {
                    bannerUrlTemp = null;
                    subList.clear();

                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
                                case VIEWTYPE_NEWS:
                                    subList.add(fc);
                                    break;

                            }
                        }
                    }
                    getBannerArray(bannerUrlTemp, VIEWTYPE_BANNER);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                JLog.e("getTvData=onErro+" + errorMsg);
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                JLog.e("getTvData=onEnd+");
                isRequesting = false;
            }
        });

    }

    public void InitBannerHolder(){
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = width * 9 / 16;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = width;
        params.height = height;
        banner.setLayoutParams(params);
        banner.setIs169(true);
        banner.setBottomWhite(getContext().getResources().getColor(R.color.no_white));
        banner.setBottomBg(R.mipmap.banner_bottom_bg, false);
    }

    public void SetBannerData(final List<NewsItem> item) {

            if (item == channelBeanList) {
                return;
            }
            if (item.size() == 1) {
                banner.setVisibility(View.GONE);
                ivPic.setVisibility(View.VISIBLE);
                tvTitle.setVisibility(View.GONE);
//                tvTitle.setText(item.getNewsItemList().get(0).getNewsTitle());
       //         GlideUtil.loadImgWith83Def(getContext(), item.get(0).getNewsImage(), ivPic);
                GlideUtil.loadImgWith83Def(getContext(), item.get(0).getNewsImage(), ivPic);

                ivPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBannerItemClick(item.get(0));
                    }
                });
                leftTitle.setVisibility(View.GONE);
//                leftTitle.setText("预告");
                titleBg.setVisibility(View.GONE);
            } else {
                leftTitle.setVisibility(View.GONE);
                titleBg.setVisibility(View.GONE);
                banner.setVisibility(View.VISIBLE);
                tvTitle.setVisibility(View.GONE);
                ivPic.setVisibility(View.GONE);
                banner.setTitlePagerChangeListener(new TitlePagerChangeListener<NewsItem>() {
                    @Override
                    public void onTitlePagetChange(TextView title, int postiton, NewsItem data) {
//                        if (data != null && !TextUtils.isEmpty(data.getDataTitle())) {
//                            title.setVisibility(View.VISIBLE);
//                            title.setText(data.getDataTitle());
//                        }
                    }
                    @Override
                    public void onTitlePagetChange(TextView leftTitle, TextView title, int postiton, NewsItem data) {

                    }
                });
                banner.setPages(new CBViewHolderCreator() {
                    @Override
                    public Object createHolder() {
                        return new BannerHolder();
                    }
                }, item)
                        //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                        .setPageIndicator(new int[]{R.mipmap.banner_icon_normal, R.mipmap.banner_icon_down})
                        //设置指示器的方向
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
                banner.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        NewsItem channelBean = channelBeanList.get(position);
                        onBannerItemClick(channelBean);
                    }
                });
                if (!banner.isTurning()) {
                    banner.startTurning(3000);
                }


            }
            channelBeanList = item;

    }

    private void onBannerItemClick(NewsItem channelBean) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();

        pairs.add(new Pair<>("位置", "大图推荐"));
        ArrayList<Pair<String, String>> tempPair = new ArrayList<>();
        tempPair.addAll(pairs);
        tempPair.add(new Pair<>("行为类型", "点击"));
        if (getActivity() != null) {
            GridsumWebDissector.getInstance().trackEvent(getActivity(), "", channelBean.getNewsTitle(), "", 200, tempPair);
        } else if (HuachengFragment.this != null) {
            GridsumWebDissector.getInstance().trackEvent(this, "", channelBean.getNewsTitle(), "", 200, tempPair);
        }
        HashMap<String, String> map = new HashMap<>();
        for (Pair<String, String> p : pairs) {
            map.put(p.first, p.second);
        }
        if (!SkipUtil.skipWithNewsItem(getContext(), channelBean, map)) {
            Toast.makeText(getContext(), "数据错误", Toast.LENGTH_SHORT).show();
        }

    }

   private void SetBannerImg(final List<NewsItem> newsItem) {

        InitBannerHolder();
        SetBannerData(newsItem);
       //GlideUtil.loadImgLarge169Def(getContext(), newsItem.getNewsImage(), caliImg);

   }

    private void getBannerArray(String url, final int mode) {

        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    SetBannerImg(newsItems);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                initCalliList();
            }
        });
    }

    public void initCalliList() {



        dataList.clear();

//        CaliItem item1 = new CaliItem("最新新闻", CaligrapherPagerAdapter.TYPE_NEWS,
//                hour24UrlTemp, channelId);
//        dataList.add(item1);

        for(FocusColumn item :subList){
            CaliItem item1 = new CaliItem(item.getDataTitle(), CaligrapherPagerAdapter.TYPE_NEWS,
                    item.getChannelUrl(), channelId);
            dataList.add(item1);
        }


//        CaliItem item2 = new CaliItem("圈子", CaligrapherPagerAdapter.TYPE_GROUP,
//                null, channelId);
//        dataList.add(item2);

        initCalliPager(dataList);


    }

        private void initCalliPager(List<CaliItem> dataList) {
            if (null == adapter) {
                adapter = new CaligrapherPagerAdapter(getContext(), getChildFragmentManager(), dataList);
                adapter.setIs_calli(true);
                viewPager.setAdapter(adapter);
                viewPager.setOffscreenPageLimit(1);
                tabLayout.setViewPager(viewPager);
            } else {
                adapter.setData(dataList);
            }
            refreshColumnTab();

            tabLayout.setOnTabSelectListener(this);
            tabLayout.setChangeSize(true);

        }

    /**
     * 刷新栏目在首页的标签
     */
    private void refreshColumnTab() {
        int size = adapter.getCount();
        if (size == 0) {
            return;
        }
        tabLayout.setTabSpaceEqual(true);
        float d = getResources().getDimension(R.dimen.tab_home_padding_m);
        if (size <= 6) {
            d = getResources().getDimension(R.dimen.tab_home_padding_l);
        } else if (size == 7) {
            d = getResources().getDimension(R.dimen.tab_home_padding);
        }
        tabLayout.setTabPaddingPx(d);
        tabLayout.notifyDataSetChanged();
//        }
    }


       @Override
       public void onTabSelect(int position) {
           viewPager.setCurrentItem(position);

       }

       @Override
       public void onTabReselect(int position) {

       }

       @Override
       public void onTabScrollTo(int position) {

       }



     @Override
     public void onDestroyView() {
         JLog.e("Cali页Destroy!");
         if (tabLayout != null) {
             tabLayout.removeAllViews();
         }
         super.onDestroyView();
     }

     @Override
     public void setUserVisibleHint(boolean isVisibleToUser) {
         super.setUserVisibleHint(isVisibleToUser);

     }


     public String getChannelUrl() {
         return channelUrl;
     }

 }


